package ace.module.product.core.impl.manager.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.model.SaveListContext;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.utils.SaveContextUtils;
import ace.cmp.util.AceStreamUtils;
import ace.module.common.core.impl.manager.impl.AbstractEntityOfAppManager;
import ace.module.product.api.model.dto.PmsCommonTagDto;
import ace.module.product.core.impl.dao.entity.PmsCommonTag;
import ace.module.product.core.impl.dao.entity.PmsProduct;
import ace.module.product.core.impl.dao.entity.PmsTag;
import ace.module.product.core.impl.dao.repository.PmsTagRepository;
import ace.module.product.core.impl.manager.PmsCommonTagManager;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 商品通用标签标记 spring data jdbc querydsl rsql manager implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class PmsCommonTagManagerImpl
    extends AbstractEntityOfAppManager<PmsCommonTag, Long, PmsCommonTagDto>
    implements PmsCommonTagManager {

  private final PmsTagRepository pmsTagRepository;

  @Override
  public SaveListContext<PmsCommonTag> assembleProductSaveListContext(PmsProduct pmsProduct, List<Long> tagIds) {
    List<PmsTag> pmsTags = pmsTagRepository.findByIdInAndPmsAppIdAndDeleteFlag(tagIds, pmsProduct.getPmsAppId(), CoreConstant.DELETE_FLAG_NOT);
    List<PmsCommonTag> pmsCommonTags = AceStreamUtils.ofNullable(pmsTags)
        .map(pmsTag -> {
          return PmsCommonTag.builder()
              .id(this.getNewId())
              .pmsAppId(pmsProduct.getPmsAppId())
              .pmsObjectId(pmsProduct.getId())
              .pmsTagId(pmsTag.getId())
              .type(pmsTag.getType())

              .deleteFlag(CoreConstant.DELETE_FLAG_NOT)
              .createTime(System.currentTimeMillis())
              .updateTime(System.currentTimeMillis())
              .rowVersion(CoreConstant.DEFAULT_ROW_VERSION)
              .build();
        })
        .collect(Collectors.toList());
    return SaveContextUtils.of(pmsCommonTags, true);
  }
}
